package com.dotfunny;

import java.util.ArrayList;
import java.util.Iterator;
import org.htmlparser.*;
import org.htmlparser.filters.*;
import org.htmlparser.util.*;

final class Engine
{
	private String _url;
	private String _type;
	private int _score;
	private StringBuffer _output = new StringBuffer();
	private Parser _parser;
	private NodeFilter _nf;
	private NodeList _nl;
	private Node _n;
	public Engine(String url, String type, int score)
	{
		try
		{
			if (url == null || type == null)
				return;
			_url = url;
			_type = type;
			_score = score;		
		}
		catch(Exception e)
		{
			_output.append(e.toString());
			return;			
		}
	}
	public String doWork()
	{
		try
		{	
			_nf = new HasAttributeFilter("class", "score");
			_parser = new Parser(_url);
			_nl = _parser.parse(_nf);
			ArrayList _al = new ArrayList();
			//store all matches in memory
			for (NodeIterator _ni = _nl.elements(); _ni.hasMoreNodes();)
			{
				_n = _ni.nextNode();
				if(_n.toPlainTextString().equals("(Score:"+_score+", "+_type+")"))
				{
					_al.add((((Tag)_n).getAttribute("id")).replace("score", "body"));
				}
			}
			//if no match, say no match and stop
			if (_al.size() == 0)
			{
				_output.append("<p>Nothing "+_type+" about this news.</p>");
				return _output.toString();
			}
			//
			_parser.reset();
			//System.out.println(_al.toString());
			for(Iterator i = _al.iterator();i.hasNext();)
			{
				String temp = (String)i.next();
				_nf = new HasAttributeFilter("name", temp.split("_")[2].toString());
				_output.append("<div id=\"dotfunny_funny_title\""+_parser.parse(_nf).elementAt(0).toHtml()+"</div>");
				//_output.append("<br>");
				_parser.reset();
				_nf = new HasAttributeFilter("id", temp);
				_output.append("<div id=\"dotfunny_funny_content\""+_parser.parse(_nf).elementAt(0).toHtml()+"</div>");
				_output.append("<br>");
				_parser.reset();
			}
			return _output.toString();
		}
		catch(Exception e)
		{
			_output.append(e.toString());
			return _output.toString();
		}
	}
}
